package com.dyj.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dyj.service.MainService;
import com.google.gson.Gson;

public class MainServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8671590049891005147L;

	private WebApplicationContext context = null;
	private Map<String, Method> methodNameMap = new HashMap<String, Method>();

	private final static String METHOD_NAME = "methodName";
	private final static String METHOD_BODY = "methodBody";

	/**
	 * Constructor of the object.
	 */
	public MainServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doRequest(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doRequest(request, response);
	}

	private void doRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		//GZIPOutputStream out = new GZIPOutputStream(response.getOutputStream());
		OutputStream out = response.getOutputStream();
		Gson gson = new Gson();

		String methodName = request.getParameter(METHOD_NAME);
		String methodBody = request.getParameter(METHOD_BODY);
		Object[] methodParameters = gson.fromJson(methodBody, Object[].class);

		MainService service = (MainService) context.getBean("mainService");
		int parametersNum = 0;
		if (methodParameters !=null){
			parametersNum = methodParameters.length;
		}
		Method method = methodNameMap
				.get(methodName + parametersNum);
		Object returnObject = null;
		String returnString = null;
		try {
			returnObject = method.invoke(service, methodParameters);
			returnString = gson.toJson(returnObject);
			byte[] returnBytes = returnString.getBytes("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentLength(returnBytes.length);
			out.write(returnBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.flush();
		out.close();
	}

	@SuppressWarnings("unused")
	private void doRequestExample(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		context = WebApplicationContextUtils
				.getWebApplicationContext(getServletContext());
		MainService service = (MainService) context.getBean("mainService");
		Method[] methods = service.getClass().getMethods();
		for (Method method : methods) {
			methodNameMap.put(method.getName()
					+ method.getParameterTypes().length, method);
		}
		Method method = methodNameMap.get("getAllProvince0");
		Object returnObject = null;
		try {
			returnObject = method.invoke(service, null);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		Gson gson = new Gson();
		System.out.print(gson.toJson(returnObject));
	}

}
